<template>
  <div class="app-container">
    <!-- 操作 -->
    <el-row style="margin-bottom: 10px;">
      <!-- 搜索 -->
      <div v-if="showSearch" class="filter-container" style="display: inline-block">
        <el-form :inline="true" :model="listQuery" class="form-inline">
          <el-form-item label="">
            <el-input v-model="listQuery.title" placeholder="标题" clearable size="small"/>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="listQuery.pid" placeholder="父类" default-first-option size="small">
              <el-option label="全部" value="-1"/>
              <el-option label="顶级" value="0"/>
              <el-option v-for="item in allCategory" :key="item.id" :label="item.html + item.title" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="listQuery.isDel" placeholder="是否删除" default-first-option clearable size="small">
              <el-option label="全部" value="-1"/>
              <el-option label="回收站" value="1"/>
              <el-option label="正常" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-waves type="primary" icon="el-icon-search" size="small" @click="handleFilter">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-waves type="warning" icon="el-icon-refresh" size="small" @click="handleFilterClear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-col :xs="24" :sm="24" :lg="24">
        <el-tooltip content="刷新" placement="top">
          <el-button v-waves type="warning" icon="el-icon-refresh" circle @click="handleFilterClear"/>
        </el-tooltip>
        <el-tooltip content="增加" placement="top">
          <el-button v-waves type="success" icon="el-icon-plus" circle @click="handleAdd"/>
        </el-tooltip>
        <el-tooltip content="搜索" placement="top">
          <el-button v-waves type="primary" icon="el-icon-search" circle @click="showSearch = !showSearch"/>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button v-waves :loading="deleting" :disabled="buttonDisabled" type="danger" icon="el-icon-delete" circle @click="handleDeleteAll"/>
        </el-tooltip>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="categoryList"
      :fit="true"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      border
      highlight-current-row
      style="width: 100%;"
      row-key="id"
      default-expand-all
      @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="分类名称" min-width="180px" fixed>
        <template slot-scope="scope">
          <span class="link-type">{{ scope.row.html }}{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类图标" min-width="80px">
        <template slot-scope="scope">
          <span class="link-type" @click="handleImg(scope.row.image)"><img :src="scope.row.image" height="40"></span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="60px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核" width="100px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleModifyStatus(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="回收站" width="100px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isDel"
            :active-value="1"
            :inactive-value="0"
            @change="handleModifyDelStatus(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180px">
        <template slot-scope="scope">
          <span>{{ scope.row.addTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-tooltip content="增加子类" placement="top">
            <el-button v-waves type="success" icon="el-icon-plus" circle @click="handleAdd(scope.row.id)"/>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button v-waves type="primary" icon="el-icon-edit-outline" circle @click="handleUpdate(scope.$index,scope.row.id)"/>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button v-waves :loading="scope.row.delete" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index,scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 100%; height: 50vh;overflow-y: scroll;">
        <el-form-item label="父分类" prop="pid">
          <el-select v-model="temp.pid" class="filter-item" placeholder="请选择">
            <el-option :value="0" label="顶级"/>
            <el-option v-for="item in allCategory" :key="item.id" :label="item.html + item.title" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="title">
          <el-input v-model="temp.title" clearable/>
        </el-form-item>
        <el-form-item label="介绍" prop="intr">
          <el-input v-model="temp.intr" clearable/>
        </el-form-item>
        <el-form-item label="缩略图" prop="image">
          <Upload v-model="temp.image" :config="config"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="temp.sort" clearable/>
        </el-form-item>
        <el-form-item label="是否审核" class="el-col-8">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否删除" class="el-col-8">
          <el-switch
            v-model="temp.isDel"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="是否隐藏" class="el-col-8">
          <el-switch
            v-model="temp.hidden"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="saveData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAll, change, delAll, getInfo, save } from '@/api/category'
import waves from '@/directive/waves'
import { getArrByKey } from '@/utils'
import openWindow from '@/utils/openWindow'
import tree from '@/utils/tree'
import myconfig from '@/config'
import Upload from '@/components/Upload/image'

export default {
  name: 'Category',
  components: { Upload },
  directives: {
    waves
  },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      selectedRows: null,
      listLoading: true,
      showSearch: false,
      listQuery: {
        title: '',
        pid: '-1',
        isDel: '-1'
      },
      buttonDisabled: true,
      deleting: false,
      currentIndex: -1,
      hasDel: false,
      // 添加/编辑
      dialogFormVisible: false,
      dialogTitle: '',
      btnLoading: false,
      temp: {
        id: 0,
        pid: '请选择',
        title: '',
        intr: '',
        image: '',
        sort: '',
        status: 1,
        isDel: 0,
        hidden: 0
      },
      config: {
        fileName: 'img',
        limit: 1,
        multiple: false,
        accept: 'image/*',
        action: myconfig.uploadUrl.img
      },
      rules: {
        pid: [{ required: true, message: '父分类', trigger: 'change' }],
        title: [{ required: true, message: '分类名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    allCategory() {
      return tree.listToTreeOne(this.list)
    },
    categoryList() {
      return tree.listToTreeMulti(this.list, 0, 'id', 'pid', 'children', { 'delete': false })
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    // 获取分类list
    fetchList() {
      this.listLoading = true
      getAll(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    // 添加
    handleAdd(pid) {
      this.dialogFormVisible = true
      this.dialogTitle = '增加'
      this.initTemp()
      if (typeof pid === 'number') {
        this.temp.pid = pid
      }
    },
    // 点击页码
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchList()
    },
    // 永久删除
    handleDeleteAll() {
      const msg = '此操作将分类及分类下文章永久删除, 是否继续?'
      if (this.selectedRows.length > 0) {
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleting = true
          const ids = getArrByKey(this.selectedRows, 'id')
          const idstr = ids.join(',')
          delAll({ ids: idstr }).then(response => {
            if (response.status === 1) {
              this.fetchList()
              this.$message.success(response.msg)
            } else {
              this.$message.error(response.msg)
            }
            this.deleting = false
          }).catch((error) => {
            this.deleting = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message.error('请选择要删除的数据')
      }
    },
    // 过滤刷新
    handleFilter() {
      this.listQuery.page = 1
      this.fetchList()
    },
    // 重置
    handleFilterClear() {
      this.listQuery = {
        title: '',
        pid: '-1',
        isDel: '-1'
      }
      this.fetchList()
    },
    // 图片预览
    handleImg(img) {
      openWindow(img, '图片预览', '500', '400')
    },
    // 删除更改(回收站)
    handleModifyDelStatus(data, index) {
      this.list[index]['isDel'] = data.isDel
      change(data.id, 'isDel', data.isDel).then(response => {
      })
    },
    // 状态更改
    handleModifyStatus(data, index) {
      this.list[index]['status'] = data.status
      change(data.id, 'status', data.status).then(response => {
      })
    },
    // 多选
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.buttonDisabled = false
      } else {
        this.buttonDisabled = true
      }
      this.selectedRows = val
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.listQuery.psize = val
      this.fetchList()
    },
    // 更新
    handleUpdate(index, id) {
      this.listLoading = true
      this.dialogTitle = '编辑'
      this.dialogFormVisible = true
      getInfo(id).then(response => {
        this.temp = response.data
        this.listLoading = false
      })
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    initTemp() {
      this.temp = {
        id: 0,
        pid: '请选择',
        title: '',
        intr: '',
        image: '',
        sort: '',
        status: 1,
        isDel: 0,
        hidden: 0
      }
    },
    saveData() {
      this.btnLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (typeof (this.temp.image) === 'object') {
            this.temp.image = this.temp.image.join(',')
          }
          save(this.temp).then(response => {
            if (response.status === 1) {
              this.fetchList()
              this.dialogFormVisible = false
              this.$message.success(response.msg)
            } else {
              this.$message.error(response.msg)
            }
            this.btnLoading = false
          }).catch((error) => {
            this.btnLoading = false
          })
        }
      })
    },
    // 排序
    sortChange(data) {
      const { prop, order } = data
      if (prop !== null) {
        this.listQuery.sort = prop + ' ' + (order === 'ascending' ? 'asc' : 'desc')
        this.fetchList()
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .text-red{
        color: red;
        cursor: pointer;
    }
    .text-green{
        color: green;
        cursor: pointer;
    }
    .item {
        margin-top: 10px;
        margin-right: 30px;
        .el-button{
            padding: 10px;
        }
    }
    .statusTitle{
        margin: 10px;
        display: inline-block;
        font-weight: 400;
    }
    /deep/ .el-dropdown-menu--medium .el-dropdown-menu__item{
        font-size: 12px;
    }
    .warning{
        text-align: center;
        .warning-icon{
            font-size: 50px;
            color: #e6a23c;
            margin-bottom: 10px;
        }
        .warning-content{
            font-size: 24px;
            font-weight: 600;
        }
    }
    .dialog-footer{
        text-align: center;
    }
    .keyword{
        display: block;
    }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
    /*图片上传*/
    /deep/ .image-uploader{
        .el-upload-list{
            .el-upload-list__item{
                width: 60px;
                height: 60px;
            }
        }
        .el-upload{
            width: 60px;
            height: 60px;
        }
    }
</style>
